package product

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"net/http"
	"strings"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAllLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductAllLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAllLogic {
	return &ProductAllLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductAllLogic) ProductAll(req *types.ProductListRequest) (resp *types.ProductsResponse, err error) {
	resp = new(types.ProductsResponse)

	//1.查询分页
	var query string
	var querys []string
	if len(req.Model) > 0 {
		querys = append(querys, fmt.Sprintf(` model like '%%%s%%'`, req.Model))
	}

	if req.ClientId > 0 {
		querys = append(querys, fmt.Sprintf(` client_id = %d`, req.ClientId))
	}

	if len(querys) > 0 {
		query = " where " + strings.Join(querys, " and ")
	}

	//queryWithLimit := query + fmt.Sprintf(" order by id desc limit %d,%d", (req.Page-1)*req.Size, req.Size)
	//products, err := l.svcCtx.ProductModel.FindByPage(l.ctx, queryWithLimit)
	products, err := l.svcCtx.ProductModel.FindByPage(l.ctx, query)
	if err != nil {
		if err == model.ErrNotFound {
			resp.Code = http.StatusNoContent
			resp.Msg = "没有数据"
			return
		}

		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return
	}

	//2.查询客户
	var clients = make(map[int64]model.Client)

	var g errgroup.Group
	for _, product := range products {
		//查询客户名称
		g.Go(func() error {
			if _, ok := clients[product.ClientId]; !ok {
				var client *model.Client
				client, e := l.svcCtx.ClientModel.FindOne(l.ctx, product.ClientId)
				if e != nil {
					fmt.Printf("[Error]客户[%d]信息错误:%s\n", client.Id, e.Error())
					return e
				}
				clients[client.Id] = *client
			}
			return nil
		})
		/*
			//查询产品价格列表
			var ps = make(map[int64][]types.ProductPriceItem, 0)
			g.Go(func() error {
				prices, e := l.svcCtx.ProductPriceModel.FindByPage(l.ctx, fmt.Sprintf(" where product_id=%d", product.Id))
				if e != nil {
					fmt.Printf("[Error]查询产品[%d]单价错误:%s\n", product.Id, e.Error())
					return e
				}

				for _, price := range prices {
					//ps = append(ps, price.Price)
					ps[price.ProductId] = append(ps[price.ProductId], types.ProductPriceItem{
						Price:     price.Price,
						CreatedAt: price.CreatedAt.Unix(),
					})

				}
				return e
			})

			if err = g.Wait(); err != nil {
				resp.Code = http.StatusInternalServerError
				resp.Msg = "服务内部错误"
				return
			}
		*/
		resp.Data = append(resp.Data, types.Product{
			Id:         product.Id,
			ClientId:   product.ClientId,
			ClientName: clients[product.ClientId].Name,
			Model:      product.Model,
			Name:       product.Name,
			Specs:      product.Specs,
			//Prices:     ps[product.Id],
			CreatedAt: product.CreatedAt.Unix(),
		})
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return
}
